// 渲染功能
async function render() {
    const { data: { data } } = await axios.get('/students')
    console.log(data);
    document.querySelector('.total').innerText = data.length
    document.querySelector('.list').innerHTML = data.map(item => `
    <tr>
        <td>${item.name}</td>
        <td>${item.age}</td>
        <td>${item.gender == 0 ? '男' : '女'}</td>
        <td>第${item.group}组</td>
        <td>${item.hope_salary}</td>
        <td>${item.salary}</td>
        <td>${item.province + item.city + item.area}</td>
        <td>
        <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen" data-id="${item.id}"></i></a>
        <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id="${item.id}"></i></a>
        </td>
    </tr>
    `).join('')
}

render()



// 删除功能
document.querySelector('.list').addEventListener('click', async function (e) {
    if (e.target.className === 'bi bi-trash') {
        if (confirm('Are you sure you want to delete this')) {
            const res = await axios.delete(`/students/${e.target.dataset.id}`)
            render()
            tip('删除成功')
        }

    }
})


// 添加功能
const modalBox = document.querySelector('#modal')
const modal = new bootstrap.Modal(modalBox)

document.querySelector('#openModal').addEventListener('click', async () => {
    modal.show()
    document.querySelector('form').reset()

    // 获取省份
    let pname
    const { data: { data } } = await axios.get('/api/province')
    document.querySelector('#province').innerHTML = `<option value="">--省份--</option>` + data.map(item => `
                <option value="${item}">${item}</option>
                `).join('')

    // 获取城市
    document.querySelector('#province').addEventListener('change', async function () {
        // 清空城市和地区
        document.querySelector('#city').value = ''
        document.querySelector('#area').value = ''
        pname = this.value
        const { data: { data } } = await axios.get('/api/city', {
            params: {
                pname
            }
        })
        document.querySelector('#city').innerHTML = `<option value="">--城市--</option>` + data.map(item => `
                <option value="${item}">${item}</option>
                `).join('')
    })


    // 获取地区
    document.querySelector('#city').addEventListener('change', async function () {
        const { data: { data } } = await axios.get('/api/area', {
            params: {
                pname,
                cname: this.value
            }
        })
        document.querySelector('#area').innerHTML = `<option value="">--地区--</option>` + data.map(item => `
                <option value="${item}">${item}</option>
                `).join('')
    })



    // 表单提交
    document.querySelector('#submit').onclick = formSub

})






async function formSub() {

    const data = serialize(document.querySelector('form'), { hash: true, empty: true })
    // console.log(data)
    // 表单校验
    if (!data.name) return tip('请输入姓名')
    if (!data.age) return tip('请输入年龄')
    if (!(+ data.age)) return tip('请输入正确的年龄')
    if (!data.group) return tip('请输入组号')
    if (!data.hope_salary) return tip('请输入期望薪资')
    if (!(+ data.hope_salary)) return tip('请输入正确期望薪资')
    if (!data.salary) return tip('请输入就业薪资')
    if (!(+ data.salary)) return tip('请输入正确就业薪资')
    if (!data.province) return tip('请输入省')
    if (!data.city) return tip('请输入城市')
    if (!data.area) return tip('请输入地区')


    data.gender = + data.gender
    data.age = + data.age
    data.group = + data.group
    data.hope_salary = + data.hope_salary
    data.salary = + data.salary

    try {
        const res = await axios.post('/students', data)
        modal.hide()
        tip('添加成功')
        document.querySelector('form').reset()
        render()

    }
    catch (err) {
        console.dir(err)
        tip('添加失败')
    }



}


// 修改功能
document.querySelector('.list').addEventListener('click', async function (e) {
    if (e.target.className === 'bi bi-pen') {
        // console.log(111)
        modal.show()
        modalBox.querySelector('.modal-title').innerHTML = '修改学员'




        const { data: { data } } = await axios.get(`/students/${e.target.dataset.id}`)
        // console.log(data)
        // console.log(document.querySelectorAll('form [name]'))


        let pname

        Array.from(document.querySelectorAll('form [name]')).forEach(async item => {
            if (item.name === 'name') item.value = data.name
            if (item.name === 'age') item.value = data.age
            if (item.name === 'group') item.value = data.group
            if (item.name === 'hope_salary') item.value = data.hope_salary
            if (item.name === 'salary') item.value = data.salary
            if (item.name === 'gender') {
                if (item.value == +data.gender) item.checked = true
            }
            if (item.name === 'province') {
                // 获取省份

                const { data: { data: prov } } = await axios.get('/api/province')
                document.querySelector('#province').innerHTML = `<option value="">--省份--</option>` + prov.map(item => `
           <option value="${item}">${item}</option>
           `).join('')
                item.value = data.province
            }
            if (item.name === 'city') {
                // 获取城市

                // 清空城市和地区
                document.querySelector('#city').value = ''
                document.querySelector('#area').value = ''
                pname = data.province
                const { data: { data: citydata } } = await axios.get('/api/city', {
                    params: {
                        pname
                    }
                })
                // console.log(citydata)
                document.querySelector('#city').innerHTML = `<option value="">--城市--</option>` + citydata.map(item => `
        <option value="${item}">${item}</option>
        `).join('')


                item.value = data.city
            }
            if (item.name === 'area') {

                // 获取地区

                const { data: { data: areadata } } = await axios.get('/api/area', {
                    params: {
                        pname,
                        cname: data.city
                    }
                })
                document.querySelector('#area').innerHTML = `<option value="">--地区--</option>` + areadata.map(item => `
        <option value="${item}">${item}</option>
        `).join('')

                item.value = data.area
            }
        })




        // 获取城市
        document.querySelector('#province').addEventListener('change', async function () {
            // 清空城市和地区
            document.querySelector('#city').value = ''
            document.querySelector('#area').value = ''
            pname = this.value
            const { data: { data } } = await axios.get('/api/city', {
                params: {
                    pname
                }
            })
            document.querySelector('#city').innerHTML = `<option value="">--城市--</option>` + data.map(item => `
            <option value="${item}">${item}</option>
            `).join('')
        })


        // 获取地区
        document.querySelector('#city').addEventListener('change', async function () {

            const { data: { data } } = await axios.get('/api/area', {
                params: {
                    pname,
                    cname: this.value
                }
            })
            document.querySelector('#area').innerHTML = `<option value="">--地区--</option>` + (data.map(item => `
            <option value="${item}">${item}</option>
            `).join(''))
            console.log(document.querySelector('#area').innerHTML)
        })


        document.querySelector('#submit').onclick = async () => {
            const formData = serialize(document.querySelector('form'), { hash: true, empty: true })
            // 表单校验
            if (!formData.name) return tip('请输入姓名')
            if (!formData.age) return tip('请输入年龄')
            if (!(+ formData.age)) return tip('请输入正确的年龄')
            if (!formData.group) return tip('请输入组号')
            if (!formData.hope_salary) return tip('请输入期望薪资')
            if (!(+ formData.hope_salary)) return tip('请输入正确期望薪资')
            if (!formData.salary) return tip('请输入就业薪资')
            if (!(+ formData.salary)) return tip('请输入正确就业薪资')
            if (!formData.province) return tip('请输入省')
            if (!formData.city) return tip('请输入城市')
            if (!formData.area) return tip('请输入地区')


            formData.gender = + formData.gender
            formData.age = + formData.age
            formData.group = + formData.group
            formData.hope_salary = + formData.hope_salary
            formData.salary = + formData.salary
            try {
                const { data: { message } } = await axios.put(`/students/${e.target.dataset.id}`, formData)
                tip(message)
                modal.hide()
                render()

            }
            catch (err) {
                tip('修改信息失败')
            }
        }
    }
})




//退出登录
const logout = document.querySelector('#logout')
logout.addEventListener('click', () => {
    // 删除本地存储里面的username和token
    if (confirm('Are you sure you want to do')) {
        localStorage.removeItem('homework-username')
        localStorage.removeItem('homework-token')
        location.href = '/login.html'
    }

})
